package com.flow.framework.registry.service.system.health.impl;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.naming.NamingService;
import com.flow.framework.common.health.ServiceHealthCheckCode;
import com.flow.framework.common.pojo.vo.system.ServiceHealthVo;
import com.flow.framework.common.service.system.health.IHealthCheckService;
import com.flow.framework.core.system.helper.SystemHealthHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;

/**
 * nacos注册中心健康检查
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/3/5
 */
@Slf4j
public class NacosRegistryCenterHealthCheckServiceImpl implements IHealthCheckService {

    private static final String UP_STATUS_STRING = "UP";

    private final NacosDiscoveryProperties nacosDiscoveryProperties;

    /**
     * 创建nacos注册中心健康检查服务
     *
     * @param nacosDiscoveryProperties nacos注册中心配置
     */
    public NacosRegistryCenterHealthCheckServiceImpl(@Autowired(required = false) NacosDiscoveryProperties nacosDiscoveryProperties) {
        this.nacosDiscoveryProperties = nacosDiscoveryProperties;
    }

    /**
     * @inheritDoc
     */
    @Override
    public List<ServiceHealthVo> check() {
        try {
            if (null == nacosDiscoveryProperties) {
                log.warn("nacos registry config is empty.");
                return Collections.singletonList(
                        SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_REGISTRY_CENTER_CODE, null, null)
                );
            }
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
            String status = namingService.getServerStatus();
            if (!UP_STATUS_STRING.equalsIgnoreCase(status)) {
                log.error("nacos registry server status error. status : {}", status);
                return Collections.singletonList(
                        SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_REGISTRY_CENTER_CODE, "nacos " + status, null)
                );
            }
            return Collections.singletonList(SystemHealthHelper.healthy(ServiceHealthCheckCode.SERVICE_REGISTRY_CENTER_CODE));
        } catch (Exception e) {
            log.error("check nacos registry error.", e);
            return Collections.singletonList(
                    SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_REGISTRY_CENTER_CODE, e.getMessage(), null)
            );
        }
    }
}
